# coding: utf-8
from typing import List

from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QHeaderView, QTableWidget, QTableWidgetItem
from qfluentwidgets import TableWidget, Action, FluentIcon as FIF, MessageBox
from qfluentwidgets.components.material import AcrylicMenu


class ViewTableWidget(TableWidget):
    clearSignal = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)

        self.verticalHeader().setVisible(False)
        self.setShowGrid(False)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Fixed)

        self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)
        self.itemDoubleClicked.connect(self.onItemDoubleClicked)

    def addItem(self, text, row, column):
        item = QTableWidgetItem(text)
        item.setToolTip(text)
        item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.setItem(row, column, item)

    def setHorizontalHeaderLabels(self, labels: List[str]):
        self.setColumnCount(len(labels))
        super().setHorizontalHeaderLabels(labels)

    def showContextMenu(self, pos):
        if self.rowCount() == 0:
            return
        menu = AcrylicMenu('', self)
        menu.addAction(Action(FIF.CLOSE, '删除选中项', triggered=self.removeSelectedRows))
        menu.addAction(Action(FIF.BROOM, '清空数据', triggered=self.clearData))
        menu.exec(self.mapToGlobal(pos))

    def removeSelectedRows(self):
        pass

    def clearData(self):
        dialog = MessageBox('清空数据', '是否清空所有数据, 这将无法恢复？', self.window())
        if dialog.exec() == dialog.DialogCode.Accepted:
            self.clearTable()
            self.clearSignal.emit()

    def clearTable(self):
        self.clearContents()
        self.setRowCount(0)

    def onItemDoubleClicked(self, item: QTableWidgetItem):
        pass
